<template>
  <view>
    <scroll-view scroll-y class="page">
      <!-- 头部 -->
      <cu-custom bgColor="bg-rgb" :isBack="true">
        <block slot="backText">返回</block>
        <block slot="content">巡检保存</block>
      </cu-custom>
      <form @submit="handleSubmit">
        <view class="cu-form-group animation-fade" :style="[{animationDelay: '.1s'}]">
          <view class="title">产线名称：{{objMsg.productlineName}}</view>
          <view>产线编号：{{objMsg.productlineCode}}</view>
        </view>
        <view class="cu-form-group animation-fade" :style="[{animationDelay: '.1s'}]">
          <view class="title">产品型号：</view>
          <input v-model="objMsg.produceTypeNum"/>
        </view>
        <view class="cu-form-group borderTop animation-slide-bottom" v-for="(item, index) in dataList" :style="[{animationDelay: (index + 1)*0.1 + 's'}]">
          <view class="flex p-xs margin-bottom-sm mb-sm borderTop" style="width: 100%">
            <view class="padding-sm radius">{{item.patrolInspectProject}}</view>
            <view class="flex-twice flex-wrap padding-sm radius">
              <template v-for="(child, childIndex) in item.child">
                <view class="flex">
                  <view class="flex-sub padding-sm">
                    {{child.patrolInspectContent}}
                  </view>
                  <view>

                  </view>
                  <view class="padding-sm">
                    <switch name="patrolUp" @change="handleSwitch(index, childIndex, $event)" :class="child.switchIndex?'checked':''" :checked="child.switchIndex?true:false"></switch>
                  </view>
                </view>

                <view class="cu-form-group animation-fade" >
                  <textarea name="patrolState" maxlength="-1"  v-model="child.patrolState" placeholder="请输入改善情况"></textarea>
                </view>
              </template>
            </view>
          </view>
          <!-- <view class="title">{{item.patrolInspectProject}}</view>
          <template v-for="child in item.child">
            <label>
              {{child.patrolInspectContent}}<switch name="inspectFunction" @change="handleSwitchGn" :class="switchGn?'checked':''" :checked="switchGn?true:false"></switch>
            </label>
          </template> -->
        </view>
        <view class="cu-form-group align-start" style="padding-top: 10px;">
          <view class="title">拍照上传（最多上传4张）</view>
          <button @tap="takephoto()" class="cu-btn bg-rgb shadow lg" style="width: 100px;">拍照上传</button>
        </view>
        <view class="picture-box">
          <view v-for="(item,index) in imglist">
            <image :src="item"></image>
            <view class="btn" @click="deleteImg(index)">删除</view>
          </view>

        </view>
        <button form-type="submit" class="btns cu-btn bg-rgb lg animation-fade" :style="[{animationDelay: (dataListLength + 1)*0.1 + 's'}]">保存</button>
      </form>
      <!-- 数据列表 -->
      <!-- 	<view class="list">
          <view class="card animation-slide-bottom" v-for="(item,index) in list" :key="index" :style="[{animationDelay: (index + 1)*0.1 + 's'}]">

            <view class="bottom">
              <view class="box">
                <view class="lable">
                  检测编码:
                </view>
                <view class="content">
                  {{item.projectCode}}
                </view>
              </view>
              <view class="box">
                <view class="lable">
                  检测名称:
                </view>
                <view class="content">
                  {{item.projectName}}
                </view>
              </view>
              <view class="boxs">
                <view class="lable">
                  <text class="title" style="background-color: red;">不良品数量：</text>
                </view>
                <view class="content">
                  <input style="width: 400rpx;" type="number" v-model="preservationList[index].num" value="" placeholder="请输入不良品数量" />
                </view>
              </view>
              <view class="boxs">
                <view class="lable">
                  <text class="title" style="background-color: #99CC00;">检测结果：</text>
                </view>
                <view class="content">
                  <textarea style="width: 400rpx;" v-model="preservationList[index].txt" value="" placeholder="请输入质检结果" />
                  </view>
              </view>
            </view>
          </view>
        </view>
        <view class="btns" v-if="list.length > 0">
          <button class="cu-btn bg-rgb lg" @click="onSubmitPrin">保存</button>
        </view> -->
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    const currentDate = this.getDate({
      format: true
    })
    return {
      date: currentDate,
      inspectGrade: "",
      materielCode: '',
      list: [],
      preservationList: [],
      objMsg:{},
      type: this.$Route.query.type,
      dataList: [],
      switchGn: false,
      imglist: [],
    }
  },
  computed: {
    dataListLength() {
      return this.dataList.length
    }
  },
  onLoad(e) {
    this.queryByType(this.type)
    this.objMsg = uni.getStorageSync('onSiteInspectionObj');
    console.log(this.objMsg)
    // this.qualityTesting()
  },
  methods: {
    deleteImg(index){
      this.imglist.splice(index,1)
    },
    takephoto() {
      let that = this
      let maxUploadNum = 4
      uni.chooseImage({
        count: maxUploadNum, // 最多可以选择的图片张数，默认4
        sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
        sourceType: ['camera', 'album'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
        success: (res) => {
          console.log(res);
          const tempFilePaths = res.tempFilePaths
          if((tempFilePaths.length + that.imglist.length) > maxUploadNum){
            return this.modal.show({
              type: 'error',
              content: '最多可上传'+ maxUploadNum +'张图片，请重新选择'
            })
          }
          tempFilePaths.forEach(item => {
            uni.uploadFile({
              url: that.$http.config.baseUrl + 'sys/common/upload',
              filePath: item,
              method: 'POST',
              name: 'file',
              header: {
                'X-Access-Token': uni.getStorageSync('Access-Token')
              },
              success: function(uploadFileRes) {
                // that.imglist = []
                that.modal.show({
                  type: 'success',
                  content: '上传成功!'
                })
                let result = JSON.parse(uploadFileRes.data)
                if (result.success) {
                  that.imglist = [result.message].concat(that.imglist); //concat追加到数组
                } else {
                  that.modal.show({
                    type: 'error',
                    content: result.message
                  })
                }
              }
            });
          })
        }
      });
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 60;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    handleSwitch(index, childIndex, e) {
      this.dataList[index].child[childIndex].switchIndex = e.detail.value
    },
    queryByType(type) {
      let _this = this
      this.$http.get('/inspect/patrolInspectTemplate/queryByType', {
        params: {type}
      }).then(res => {
        if(res.data.success) {
          let resData = res.data.result
          let dataInfo = {}
          resData.forEach((item, index) => {
            item.switchIndex = true
            item.patrolState = ''
            let { patrolInspectProject } = item;
            if (!dataInfo[patrolInspectProject]) {
              dataInfo[patrolInspectProject] = {
                patrolInspectProject,
                child: []
              }
            }
            dataInfo[patrolInspectProject].child.push(item);
          });
          this.dataList = Object.values(dataInfo);
          console.log('list:',this.dataList)

        } else {
          this.modal.show({ type:'error', content:res.data.message })
        }
        console.log('分类查询：', res)
      })
    },
    qualityTesting() {
      uni.showLoading({
        mask:true,
        title:'加载中.....'
      })
      let data = {
        inspectGrade: '巡检',
        materielCode: this.objMsg.mechanismCode
      }
      this.$http.get('inspect/mesMaterielCheckprojrct/getByGrade', {
        params: data
      }).then(res => {
        uni.hideLoading()
        if (res.data.success) {
          this.list = res.data.result
          for (let i = 0; i < this.list.length; i++) {
            let data = {
              num: '',
              txt: '',
              id: this.list[i].id,
              name:this.list[i].projectName,
              code:this.list[i].projectCode
            }
            this.preservationList.push(data)
          }
        } else {
          // this.$tip.error(res.data.message)
          this.modal.show({ type:'error', content:res.data.message })
        }
      })
    },
    handleSubmit(e) {
      console.log('x:', this.dataList)
      let patrolInspectLogs = []
      let isDone = false
      this.dataList.every((item, index) => {
        return item.child.every((child, childIndex) => {
          if (child.switchIndex === false && child.patrolState.trim().length === 0) {
            this.modal.show({ type:'error', content: '请输入改善情况' })
            isDone = true
            return false
          } else {
            delete child.id
            delete child.createBy
            delete child.createTime
            child.inspectDate = this.date
            child.lineType = this.objMsg.productlineCode
            patrolInspectLogs.push({
              ...child
            })
            return true
          }

        })
      })
      if (isDone) {
        return
      }
      let image = ''
      this.imglist.forEach((item,index)=>{
        if(this.imglist[index+1]){
          image += item + ','
        }else{
          image += item
        }
      })
      patrolInspectLogs.forEach(item => {
        item.patrolUp = item.switchIndex + ''
        item.produceTypeNum = this.objMsg.produceTypeNum
        item.inspectImg = image
        return item
      })
      console.log('patrolInspectLogs', patrolInspectLogs)

      let params = patrolInspectLogs
      uni.showLoading({
        mask:true,
        title:'保存中.....'
      })
      this.$http.post('inspect/patrolInspectMain/add', params).then(res => {
        uni.hideLoading()
        if (res.data.success) {
          this.modal.show({ type:'success', content:res.data.message })
          setTimeout(function() {
            uni.navigateBack({
              delta: 1
            })
          }, 1000);
        } else {
          // this.$tip.error(res.data.message)
          this.modal.show({ type:'error', content:res.data.message })
        }
      })
    },
    onSubmitPrin(){
      uni.showModal({
        title: '提示',
        content: '本次质检是否合格',
        cancelText: '不合格',
        confirmText: '合格',
        success: res => {
          if (res.confirm) {
            uni.showModal({
              title: '质检保存',
              content: '确定要保存本次质检合格记录？',
              cancelText: '取消',
              confirmText: '确定',
              success: res => {
                if (res.confirm) {
                  uni.showLoading({
                    mask:true,
                    title:'保存中.....'
                  })
                  let obj ={
                    inspectGrade: this.objMsg.produceGrade,
                    materielCode: this.objMsg.mechanismCode,
                    materielName: this.objMsg.mechanismName,
                    relatedCode: this.objMsg.id,
                    inspectQualify:'是',
                    mesBadnessInfoList:[]
                  }
                  for(let i = 0 ; i <this.preservationList.length;i++){
                    let data ={
                      inspectProject: this.preservationList[i].code + '-' +this.preservationList[i].name,
                      inspectResult:this.preservationList[i].txt,
                      query2:this.preservationList[i].num
                    }
                    obj.mesBadnessInfoList.push(data);
                  }
                  this.$http.post('inspect/mesBadnessHandle/appAdd', obj).then(res => {
                    uni.hideLoading()
                    if (res.data.success) {
                      // this.$tip.success(res.data.message);
                      this.modal.show({ type:'success', content:res.data.message })
                      setTimeout(function() {
                        uni.navigateBack({
                          delta: 1
                        })
                      }, 1000);
                    } else {
                      // this.$tip.error(res.data.message)
                      this.modal.show({ type:'error', content:res.data.message })
                    }
                  })
                }
              }
            })
          }else{
            uni.showModal({
              title: '质检保存',
              content: '确定要保存本次质检不合格记录？',
              cancelText: '取消',
              confirmText: '确定',
              success: res => {
                if (res.confirm) {
                  uni.showLoading({
                    mask:true,
                    title:'保存中.....'
                  })
                  let obj ={
                    inspectGrade: this.objMsg.produceGrade,
                    materielCode: this.objMsg.mechanismCode,
                    materielName: this.objMsg.mechanismName,
                    relatedCode: this.objMsg.id,
                    inspectQualify:'否',
                    mesBadnessInfoList:[]
                  }
                  for(let i = 0 ; i <this.preservationList.length;i++){
                    let data ={
                      inspectProject: this.preservationList[i].code + '-' +this.preservationList[i].name,
                      inspectResult:this.preservationList[i].txt,
                      query2:this.preservationList[i].num
                    }
                    obj.mesBadnessInfoList.push(data);
                  }
                  this.$http.post('inspect/mesBadnessHandle/appAdd', obj).then(res => {
                    uni.hideLoading()
                    if (res.data.success) {
                      // this.$tip.success(res.data.message);
                      this.modal.show({ type:'success', content:res.data.message })
                      setTimeout(function() {
                        uni.navigateBack({
                          delta: 1
                        })
                      }, 1000);
                    } else {
                      // this.$tip.error(res.data.message)
                      this.modal.show({ type:'error', content:res.data.message })
                    }
                  })
                }
              }
            })
          }
        }
      })
    }
  },
}
</script>

<style lang="less">
.page {
  padding-bottom: 80rpx;
}
.card {
  margin: 30rpx;
  box-shadow: 0px 0px 5rpx 2rpx rgba(0, 0, 0, 0.1);
  border-radius: 10rpx;
  padding: 30rpx;
  background-color: white;
}

.card .top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1rpx solid #F0F0F0;
  padding-bottom: 20rpx;
  font-weight: bold;
}

.card .bottom .box {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
}

.card .bottom .box .lable {
  width: 25%;
}

.card .bottom .box .content {
  width: 74%;
  text-align: right;
}
.boxs{
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0;
  align-items: center;
}
.boxs .title{
  font-weight: bold;
  padding: 10rpx;
  border-radius: 10rpx;
  color: white;;
}
.boxs input {
  border: 2rpx solid red;
  height: 60rpx;
  padding: 10rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
  color: red;
}
.boxs input .input-placeholder{
  color: red;
}
uni-textarea{
  border: 2rpx solid #F0F0F0;
  padding: 10rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
}
.list{
  margin-bottom: 120rpx;
}
.btns{
  position: fixed;
  z-index: 999;
  background: white;
  bottom: 0;
  height: 80rpx;
  line-height: 100rpx;
}
.cu-btn{
  width: 650rpx;
  margin-left: 50rpx;
}
.picture-box {
  width: 100%;
  margin-top: 10px;
  padding: 0 20rpx;

  .picture {
    width: 100%;
    height: 200px;
    margin-bottom: 10px;
  }
  .btn {
    width: 180rpx;
    height: 64rpx;
    margin-bottom: 8rpx;
    line-height: 50rpx;
    color: white;
    border-radius: 30rpx;
    padding: 10rpx 20rpx;
    text-align: center;
    background-image: radial-gradient(circle, #3F55E9, #5F71ED, #7D8CF0);
  }
}
</style>
